package com.honey.feature.xml;

import java.io.IOException;
import java.io.Reader;

public class XmlContent {
	
	private Reader reader;
	
	private int _a1_1=0;
	
	private int _a2_2=0;

	private int _a3_3=0;
	
	private int _a4_4=0;
	
	private int _b1_1=0;
	
	private int _b2_2=0;
	
	private int _b3_3=0;
	
	private boolean start=false ;
	
	private int n =0;
	
	public XmlContent(Reader reader ){
		this.reader = reader ;
	}
	
	public  final String getContent() throws IOException{
		StringBuilder sb = new StringBuilder();
		char[] buffer = new char[1]; 
		char c= '\0' ;
		while((reader.read(buffer)) !=-1){
			n ++ ;
			c = buffer[0] ;
			switch( c){
				case '<':
					_a1();break;
				case '!':
					_a2();break;
				case '-':
					_a3_b2();break;
				case '>':
					_b3();break;

			}
			if( start() && !start){
				int length = sb.length();
				sb.setLength( length - 3 );
				start = true;
			}else if(end()){
				start = false;
				clean();
			}
			else if( !start && c !=' ' && c !='\n' && c !='\r'&& c !='\t' ){
				sb.append(c);
			}
		}
		return sb.toString();
	}
	private final boolean start(){
		return _a4_4-_a3_3==1 && _a3_3-_a2_2==1 && _a2_2-_a1_1==1 ;
	}
	
	private final boolean end(){
		return _b3_3-_b2_2==1 && _b2_2-_b1_1==1 ;
	}
	
	private final void _b3(){
		if( _b2_2-_b1_1==1 && n - _b2_2 == 1 ){
			_b3_3 =n;
		}else{
			_b1_1=0; // -
			_b2_2=0; // -
			_b3_3=0; // >
		}
	}
	
	private final void _a1(){
		_a1_1 = n;
	}
	
	private final  void _a2(){
		if(n-_a1_1==1 ){
			_a2_2 = n;
		}else{
			clean();
		}
	}
	
	private  final void _a3_b2(){
		if( start() ){
			if( n - _b1_1 != 1 ){
				_b1_1 = n ;
			}else if( n - _b1_1  == 1){
				_b2_2 =n;
			}
		}else{
			if( n-_a3_3 == 1){
				_a4_4 = n;
				return ;
			}else if(n-_a2_2 == 1){
				_a3_3 = n;
				return ;
			}
			clean();
		}
	}
	
	private final void clean(){
		_a1_1=0; //<
		_a2_2=0; // !
		_a3_3=0; // -
		_a4_4=0; // -
		_b1_1=0; // -
		_b2_2=0; // -
		_b3_3=0; // >
	}
	
}
